package untiring07.j2ee.advanced;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(urlPatterns={"/sungjuk_input","/sungjuk_save","/sungjuk_list"})
public class J05HelloModel2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	// doGet(),doPost()를 처리하는 메서드	
	private void process(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String dispatchUrl = null;
		String url = req.getRequestURI();
		int lastIndex = url.lastIndexOf("/");
		String action = url.substring(lastIndex+1);
		//분석한 action에 따라 작없을 분배함
		if(action.equals("sungjuk_input")){
		}else if(action.equals("sungjuk_save")){
			String name =req.getParameter("name");
			int kor = Integer.parseInt(req.getParameter("kor"));
			int eng = Integer.parseInt(req.getParameter("eng"));
			int mat = Integer.parseInt(req.getParameter("mat"));
			int tot = kor+eng+mat;
			float avg = tot/3;
			String grd = "가"; 
			switch((int)avg/10){
			case 10: 
			case 9: grd="수";break;
			case 8: grd="우";break;
			case 7: grd="미";break;
			case 6: grd="양";
			};
			// 서블릿에서 생성된 결과값을 forward된 JSP페이지에 출력하기 위해 
			// request 영역에 변수로 저장
			req.setAttribute("name", name);
			req.setAttribute("kor", kor);
			req.setAttribute("eng", eng);
			req.setAttribute("mat", mat);
			req.setAttribute("tot", tot);
			req.setAttribute("avg", avg);
			req.setAttribute("grd", grd);
		}else if(action.equals("sungjuk_list")){
		}
		
		// 작업이 끝난 후 처리 결과를 출력할 페이지 지정
		if(action.equals("sungjuk_input")){
			dispatchUrl = "J05sungjukinput.jsp";
		}else if(action.equals("sungjuk_save")){
			dispatchUrl = "J05sungjuklist.jsp";
		}else if(action.equals("sungjuk_list")){
			dispatchUrl = "J05sungjuklist.jsp";
		}
		// 지정한 페이지로 forward
		if(dispatchUrl != null){
			RequestDispatcher rd = req.getRequestDispatcher(dispatchUrl);
			rd.forward(req, res);
			//res.sendRedirect("/JSP_Advanced/"+dispatchUrl);
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	process(req,res);
		
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
	process(req,res);
	}

}
